//
//  ZCComposeTextView+Extension.swift
//  weibo
//
//  Created by Ning Xie on 16/8/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

extension ZCComposeTextView {
    
    var emoticonText:String?{
        
        var result = ""
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (info, range, stop) in
            
            if let attechment = info["NSAttachment"] as? ZCTextAttachment{
                
                let emoticon = attechment.emoticonModel!
                result += emoticon.chs!
                
            }else{
                result += self.attributedText.attributedSubstringFromRange(range).string
            }
            
        }
        return result
    }
 
    func insertEmoticon(emoticon:ZCEmoticonModel){
        
        if emoticon.type == "0" {
            
            let originalAttributedStr = NSMutableAttributedString(attributedString: self.attributedText)
            
//            let image = UIImage(named: (emoticon.path)!)
//            let attachment = ZCTextAttachment()
//            attachment.emoticonModel = emoticon
//            let fontHeight = self.font!.lineHeight
//            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
//            attachment.image = image
//            let attributed = NSAttributedString(attachment: attachment)
            
            //            originalAttributedStr.appendAttributedString(attributed)
            let attributed = NSAttributedString.attributedStringWithEmoticon(emoticon, font: self.font!)
            var range = self.selectedRange
            originalAttributedStr.replaceCharactersInRange(range, withAttributedString: attributed)
            originalAttributedStr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, originalAttributedStr.length))
            
            self.attributedText = originalAttributedStr
            range.location += 1; range.length = 0
            self.selectedRange = range
            
        }else{
            self.insertText(((emoticon.code)! as NSString).emoji())
        }
        NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
        self.delegate?.textViewDidChange?(self)

    }
    
    
    
    
    
}
